class Solution
{
public:
    int lastStoneWeightII(vector<int>& stones)
    {
        int n = stones.size();
        int sum = accumulate(stones.begin(), stones.end(), 0);
        int aim = sum / 2;
        vector<int> dp(aim + 1, 0);
        for (int i = 1; i <= n; i++)
        {
            for (int j = aim; j >= stones[i - 1]; j--)
            {
                dp[j] = max(dp[j], dp[j - stones[i - 1]] + stones[i - 1]);
            }
        }
        return sum - 2 * dp[aim];
    }
};